package com.swak.validator;

import com.swak.asm.FieldCache.FieldMeta;
import com.swak.validator.process.Processor;
import com.swak.validator.process.impl.EmailProcessor;
import com.swak.validator.process.impl.IdcardProcessor;
import com.swak.validator.process.impl.LengthProcessor;
import com.swak.validator.process.impl.MaxProcessor;
import com.swak.validator.process.impl.MinProcessor;
import com.swak.validator.process.impl.NameProcessor;
import com.swak.validator.process.impl.NotNullProcessor;
import com.swak.validator.process.impl.PhoneProcessor;
import com.swak.validator.process.impl.RangeProcessor;
import com.swak.validator.process.impl.RegexProcessor;

/**
 * 简单的验证器
 *
 * @author: lifeng
 * @date: 2020/3/29 15:37
 */
public class SmartValidator implements Validator {

	private final ThreadLocal<Processor> holder = new ThreadLocal<Processor>() {
		@Override
		protected Processor initialValue() {
			return create();
		}
	};

	private Processor create() {
		Processor processor = new NotNullProcessor();
		LengthProcessor lengthProcessor = new LengthProcessor();
		MaxProcessor maxProcessor = new MaxProcessor();
		MinProcessor minProcessor = new MinProcessor();
		EmailProcessor emailProcessor = new EmailProcessor();
		PhoneProcessor phoneProcessor = new PhoneProcessor();
		IdcardProcessor idcardProcessor = new IdcardProcessor();
		NameProcessor nameProcessor = new NameProcessor();
		RegexProcessor regexProcessor = new RegexProcessor();
		RangeProcessor rangeProcessor = new RangeProcessor();
		processor.next(lengthProcessor).next(maxProcessor).next(minProcessor).next(emailProcessor).next(phoneProcessor)
				.next(idcardProcessor).next(nameProcessor).next(regexProcessor).next(rangeProcessor);
		return processor;
	}

	/**
	 * 链式处理校验
	 */
	@Override
	public String validate(FieldMeta field, Object value, String group) {
		return holder.get().process(field, value, group);
	}
}